<template>
  <ElementDialog
    :visible.sync="show"
    class="ui-dialog"
    :dialog-title="!form.id ? '新建消息对象' : '修改消息对象'"
    :fullscreen="fullScreen"
    width="90%"
    top="5vh"
    @close="closeDialog"
    @open="handleOpenBefore">
    <template #title>
      <div class="avue-crud__dialog__header">
        <span class="el-dialog__title">{{ dialogTitle }}</span>
        <div class="avue-crud__dialog__menu">
          <i
            style="cursor: pointer"
            :class="['el-dialog__close', fullScreen ? 'el-icon-news' : 'el-icon-full-screen']"
            @click="fullScreen = !fullScreen"></i>
        </div>
      </div>
    </template>
    <template #default>
      <div
        style="min-height: 300px; overflow-x: hidden"
        class="flex-column"
        :style="{ height: fullScreen ? '100%' : '500px' }">
        <div class="ui-block">
          <ElForm ref="form" :label-position="labelPosition" label-width="80px" :model="form" style="padding: 10px">
            <NavTabPanel>
              <ElTabPane class="my-panel" label="基本信息">
                <ElRow>
                  <ElCol :span="12">
                    <ElFormItem
                      v-if="!subjectDisabled"
                      label="所属消息"
                      prop="subject"
                      :rules="[{ required: true, message: '请选择消息信息' }]">
                      <ElInput
                        v-model="form.subject"
                        :disabled="subjectDisabled"
                        placeholder="请选择消息信息"
                        @focus="subjectClick" />
                    </ElFormItem>
                  </ElCol>
                  <ElCol :span="2" />
                  <ElCol :span="10">
                    <ElCheckbox
                      :value="subjectDisabled"
                      style="padding-left: 20px"
                      label="自定义"
                      border
                      @change="handleChangeStrategy" />
                  </ElCol>
                </ElRow>
                <ElRow>
                  <FyForm
                    v-if="subjectDisabled"
                    ref="avueForm"
                    v-model="dataForm"
                    :defaults.sync="defaults"
                    :option="formOption"
                    @submit="dataFormSubmit" />
                </ElRow>
                <ElRow>
                  <ElCol :span="24">
                    <ElRow>
                      <ElCol :span="20">
                        <p style="padding: 0 10px">消息对象-用户信息</p>
                      </ElCol>
                      <ElCol :span="4">
                        <ElButton type="primary" class="el-icon-circle-plus" :disabled="disabled" @click="add"
                          >添加</ElButton
                        >
                        <ElButton type="primary" class="el-icon-delete" :disabled="disabled" @click="del"
                          >删除所选</ElButton
                        >
                      </ElCol>
                    </ElRow>
                    <ElTable v-if="!formDisabled" :data="rows" border style="width: 100%" @selection-change="onChange">
                      <ElTableColumn type="selection" width="55" />
                      <ElTableColumn prop="username" label="登录帐号" width="240" />
                      <ElTableColumn prop="realName" label="用户姓名" width="240" />
                      <ElTableColumn prop="deptName" label="单位名称" width="240" />
                      <ElTableColumn prop="email" label="邮箱" width="240" />
                      <ElTableColumn prop="realPhone" label="手机号" width="240" />
                    </ElTable>
                  </ElCol>
                </ElRow>
                <SelectMessageManagement :visible.sync="isPickerShow" @getMessageManagement="getMessageManagement" />
                <SelectMultipleUser :visible.sync="visibleUser" @getUserList="getUserList" />
              </ElTabPane>
            </NavTabPanel>
          </ElForm>
        </div>
      </div>
    </template>
    <template #footer>
      <ElButton type="primary" @click="dataFormSubmit">确 定</ElButton>
      <slot name="footer"></slot>
    </template>
  </ElementDialog>
</template>

<script>
  import { fetchList, addObsaveMessageUserObjectBatchj } from '@/api/message/messageuserobject'
  import { getAllDocTypeOption } from '@/api/admin/doctype'
  import { jobAll } from '@/api/daemon/sys-job'
  import { messageCtiTree } from '@/api/message/messagecti'
  import { messageManagementAdd } from '@/api/message/messagemanagement'
  import SelectMultipleUser from '@/components/user/SelectMultipleUser'
  import SelectMessageManagement from '@/components/message/SelectMessageManagement'
  import NavTabPanel from '@/components/ui/NavTabPanel'
  import { formOption } from '@/const/crud/message/messagemanagement'

  export default {
    name: 'DlgMessageUserObjectForm',
    components: { SelectMultipleUser, NavTabPanel, SelectMessageManagement },
    props: {
      sourceId: {
        type: String
      },
      formDisabled: {
        type: Boolean
      },
      sourceType: {
        type: String,
        default: ''
      },
      docCode: {
        type: String,
        default: ''
      }
    },

    data() {
      return {
        visibleUser: false,
        isPickerShow: false,
        rows: [],
        selectedRows: [],
        labelPosition: 'right',
        form: {
          messageManagementId: '',
          subject: '',
          sourceId: '',
          sourceType: '',
          userList: []
        },
        dialogTitle: '',
        disabled: false,
        subjectDisabled: false,
        show: false,
        fullScreen: true,
        dataForm: {
          id: 0,
          unid: '',
          createId: '',
          createBy: '',
          createTime: '',
          deptId: '',
          deptFullname: '',
          updateBy: '',
          updateTime: '',
          tenantId: '',
          delFlag: '',
          subject: '',
          doctype: '',
          sourceid: '',
          ctiId: '',
          ctiName: '',
          ctiFullname: '',
          ctiFullcode: '',
          status: '0',
          infor: '',
          openUrl: '',
          openType: 'N',
          remarks: '',
          timelimitType: '0',
          startdate: '',
          enddate: '',
          mode: ''
        },
        docTypeOptions: [],
        jobOptions: [],
        treeCtiData: [],
        visibleTimelimitType: false,
        formOption,
        defaults: {}
      }
    },
    watch: {
      show(val) {
        this.show = val // 新增isVisible的watch，监听变更并同步到IsShowPage上
      },
      sourceId(val) {
        // eslint-disable-next-line vue/no-mutating-props
        this.sourceId = val
      },
      'dataForm.timelimitType'(val) {
        if (val === 0) {
          this.defaults.startdate.display = false
          this.defaults.enddate.display = false
        } else {
          this.defaults.startdate.display = true
          this.defaults.enddate.display = true
        }
      }
    },
    created() {
      // this.init()
    },
    methods: {
      init(sourceId) {
        this.form.sourceId = sourceId
        this.subjectDisabled = false
        // 长期坚持
        if (this.dataForm.timelimitType === '0') {
          this.visibleTimelimitType = false
        } else {
          // 周期完成
          this.visibleTimelimitType = true
        }
        this.initData()
      },
      initData() {
        this.show = true
        getAllDocTypeOption().then(res => {
          this.docTypeOptions = res.data.data
          for (let i = 0; i < this.docTypeOptions.length; i++) {
            if (this.docTypeOptions[i].docType === this.sourceType && this.docTypeOptions[i].docCode === this.docCode) {
              // 文档id
              this.dataForm.sourceid = this.docTypeOptions[i].id
              // 文档名称
              this.dataForm.doctype = this.docTypeOptions[i].docName
              this.dataForm.openUrl = this.docTypeOptions[i].path
              break
            }
          }
        })
        jobAll().then(res => {
          this.jobOptions = res.data.data
        })

        messageCtiTree().then(res => {
          this.treeCtiData = res.data.data
        })
      },
      getPage(page) {
        return fetchList({ current: page.page, size: page.limit })
      },
      subjectClick(rows) {
        this.isPickerShow = true
      },
      getUserList(userList) {
        this.rows = userList
      },
      getMessageManagement(rows) {
        this.form.managementid = rows.id
        this.form.subject = rows.subject
      },
      onChange(rows) {
        this.selectedRows = rows
      },
      del() {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要要删除的用户信息！')
          return
        }
        const deleteIds = []
        this.selectedRows.forEach(row => {
          if (row.userId > 0) {
            deleteIds.push(row.userId)
          }
        })
        const _this = this
        this.$confirm(`是否确认删"${deleteIds.length} "条明细数据，提示`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(function () {
            _this.rows = _this.rows.filter(value => !_this.selectedRows.includes(value))
            _this.form.userList = _this.form.userList.filter(value => !_this.selectedRows.includes(value))
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      add() {
        this.visibleUser = true
      },
      confirm() {},
      handleOpenBefore() {
        this.form.subject = ''
        this.form.managementid = ''
        this.form.userList = []
        this.selectedRows = []
        this.rows = []
        // this.form.sourceId = this.sourceId
        this.form.sourceType = this.sourceType
      },
      dataFormSubmit() {
        if (!this.subjectDisabled) {
          this.$refs.form.validate(valid => {
            if (valid) {
              if (this.rows === null || this.rows.length <= 0) {
                this.$message.warning('请选择用户信息!')
                return
              }
              this.form.userList = this.rows
              if (valid) {
                const row = this.form
                addObsaveMessageUserObjectBatchj(row).then(data => {
                  this.$message.success('添加成功')
                  this.show = false
                  this.$emit('refreshDataList')
                })
              }
            }
          })
        } else {
          this.$refs.avueForm.validate((valid, done, msg) => {
            if (valid) {
              if (this.rows === null || this.rows.length <= 0) {
                this.$message.warning('请选择用户信息!')
                done()
                return
              }
              this.form.userList = this.rows

              this.dataForm.doctype = this.dataForm.$sourceid
              this.dataForm.jobName = this.dataForm.$jobId
              this.dataForm.mode = this.dataForm.modes.join(',').toString()

              this.dataForm.userObject = this.form
              messageManagementAdd(this.dataForm).then(res => {
                this.$message.success('添加成功')
                this.show = false
                this.$emit('refreshDataList')
              })
            }
          })
        }
      },
      closeDialog() {
        this.$refs.form.resetFields()
        this.form.subject = ''
        this.form.managementid = ''
        this.form.userList = []
        this.selectedRows = []
        this.rows = []
        this.subjectDisabled = false
      },
      handleChangeStrategy(val) {
        this.subjectDisabled = val
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-table th > .cell.quantity {
    color: red;
    font-weight: normal;
    font-size: 12px;
  }
</style>
